import { request } from '@inbiz/utils';
import { DownloadTmplType, ExportType, ImportType, ImodelDetail } from '../../interfaces';

const apiPrefix = `/inbiz/api/services/front/modelengine/v${InbizConfig.API_VERSION}`;
const apiHashPrefix = `/inbiz/api/hash/services/front/modelengine/v${InbizConfig.API_VERSION}`;
const cardTmplPrefix = `/inbiz/api/services/staticresource/v${InbizConfig.API_VERSION}/file/system`;
const saveSearchPrefix = `/inbiz/api/services/front/engines/v${InbizConfig.API_VERSION}/userConfig`;

type CardTmplType = { file: any; appId: string };
const tableApi = {
  uploadCardTmpl: ({ file, appId }: CardTmplType) => {
    const formData = new FormData();
    formData.append('file', file);
    return request.post(`${cardTmplPrefix}/${appId}?groupName=jsx`, {
      data: formData,
    });
  },
  downloadCardTmpl: (path: string) => {
    return request
      .get(`${path}?raw`, {
        responseType: 'blob',
      })
      .then((res) => {
        downFile(res, '模板.jsx');
        return res;
      });
  },
  exportTable: (exportParam: ExportType) => {
    const {
      fields,
      appId,
      sourceModel,
      fileName,
      recordIds,
      importUpdate = false,
      fileType,
      conditions,
      pageInfo,
      orderInfo,
    } = exportParam;
    const api = `${apiHashPrefix}/modelQueryAdapter/queryTableDataExport`;
    const params = {
      appId,
      key: sourceModel,
      proConfig: JSON.stringify(fields),
      fileName,
      isUpdate: importUpdate,
      fileType,
      recordIds,
      modelQueryDataInput: {
        appId,
        key: sourceModel,
        conditions,
        pageInfo: recordIds ? pageInfo : null,
        orderInfo,
        lazyModel: null,
      },
    };
    return request.post(api, {
      requestType: 'json',
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
  },
  getFile: (filePath: string, key: string) => {
    return request
      .get(`${apiHashPrefix}/modelQueryAdapter/exportedFile`, {
        requestType: 'json',
        responseType: 'blob',
        headers: {
          'Content-Type': 'application/json',
        },
        params: {
          filePath,
          key,
        },
      })
      .then((res) => {
        downFile(res, filePath?.substring(filePath.indexOf('_') + 1));
        return res;
      });
  },
  importTable: (importParam: ImportType) => {
    const { file, fields, appId, sourceModel, importUpdate = false } = importParam;
    const api = `${apiHashPrefix}/modelQueryAdapter/queryTableDataImport`;
    const formData = new FormData();
    const param = {
      appId,
      key: sourceModel,
      proConfig: JSON.stringify(fields),
      isUpdate: importUpdate,
    };
    Object.keys(param).forEach((key) => {
      formData.append(key, param[key]);
    });
    formData.append(file.name, file as any);
    return request.post(api, {
      data: formData,
    });
  },
  downloadTemplate: (downloadTmplParam: DownloadTmplType) => {
    const {
      fields,
      appId,
      sourceModel,
      fileName = '导入模板.xlsx',
      importUpdate = false,
    } = downloadTmplParam;
    const api = `${apiPrefix}/modelQueryAdapter/QueryDownLoadTemplate`;
    const param = {
      appId,
      key: sourceModel,
      proConfig: JSON.stringify(fields),
      fileName,
      isUpdate: importUpdate,
    };
    return request
      .post(api, {
        requestType: 'json',
        responseType: 'blob',
        headers: {
          'Content-Type': 'application/json',
        },
        data: param,
      })
      .then((res: any) => {
        downFile(res, '导入模板.xlsx');
      });
  },
  getProgress: (key: string) => {
    const api = `${apiHashPrefix}/modelQueryAdapter/processInfo?key=${key}`;
    return request.get(api);
  },
  delModelData: (delParam: { appId?: string; modelKey?: string; id: string }): Promise<boolean> => {
    const { appId, modelKey, id } = delParam;
    return request.post(`${apiPrefix}/businessData/batchDeleteData`, {
      data: {
        modelKey,
        recordIds: id,
        appId,
      },
    });
  },
  getRelationModels: (appId: string, modelKey: string) => {
    return request.get(`${apiPrefix}/control/relationModels?appId=${appId}&modelKey=${modelKey}`);
  },
  getManyFields: (appId: string, modelKey: string) => {
    var modelKeys = modelKey.split('&modelKeys=');
    return request(`/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/model/manyFields`, {
      method: 'post',
      data: {
        appId,
        modelKeys,
      },
    });
  },
  delInterfaceData: (data: any) => {
    const api = `${apiPrefix}/businessData/deleteInterface`;
    return request.post(api, {
      data,
    });
  },
  downloadFile: downFile,
  changeDataSort: (params: any) => {
    return request.post(
      `/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/modelQueryAdapter/changeDataSort`,
      {
        timeout: 10000,
        data: params,
      },
    );
  },
  saveTableSearch: (inbiz: any, configValue: string) => {
    const appInfo = inbiz?.appInfo;
    const data = {
      appId: appInfo?.appId || '',
      siteOutId: appInfo?.OutId || '',
      pageOutId: inbiz?.pageId,
      configValue
    }
    return request.post(`${saveSearchPrefix}/saveTableCondition`, { data });
  },
  getTableSearch: (params: {
    appId: string;
    siteOutId: string;
    pageOutId: string;
  }) => {
    return request.get(`${saveSearchPrefix}/userTableSearchCondition`, { params });
  },
  // 获取查询器详情
  findModelQuery: async (params: {
    key: string;
    appId: string;
  }): Promise<ImodelDetail> => {
    return await request(
      `/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/modelQuery/queryInfo`,
      {
        params,
        // 查询器工厂的请求头所需要的appId
        headers: {
          appId: params.appId,
        },
      },
    ).catch((e) => {
      console.warn(params.key, '查询器不存在');
      return {
        id: params.key,
        appId: params.appId,
        ModelQueryConfig: {
          ModelQueryModelRelation: [],
          ModelQueryField: [],
          SortConfigs: [],
          FixedCondition: [],
        },
      };
    });
  }
};

function downFile(blob: Blob, filename: string) {
  if ((window.navigator as any).msSaveOrOpenBlob) {
    (navigator as any).msSaveBlob(blob, filename);
  } else {
    const link = document.createElement('a');
    const body = document.querySelector('body');

    link.href = window.URL
      ? window.URL.createObjectURL(blob)
      : window.webkitURL.createObjectURL(blob);
    link.download = filename;
    // fix Firefox
    link.style.display = 'none';
    body!.appendChild(link);

    link.click();
    body!.removeChild(link);

    window.URL
      ? window.URL.revokeObjectURL(link.href)
      : window.webkitURL.revokeObjectURL(link.href);
  }
}
export default tableApi;
